package com.browan.constellation.weibo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;


public class Hmac_Sha1
{
	private static final String HMAC_SHA1 = "HmacSHA1";

	public static String generateSignature(String data)
	{
		byte[] byteHMAC = null;
		try
		{
			// SignatureMethod.HMAC_SHA1
			Mac mac = Mac.getInstance(HMAC_SHA1);
			String oauthSignature = encode(AppManager.APP_SECRET) + "&";
			SecretKeySpec spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1);
			mac.init(spec);
			byteHMAC = mac.doFinal(data.getBytes());
		}
		catch (InvalidKeyException e)
		{
			e.printStackTrace();
		}
		catch (NoSuchAlgorithmException ignore)
		{
			ignore.printStackTrace();
		}
		return BASE64Encoder.encode(byteHMAC);
	}

	/**
	 * 把一些经过URLEncoder转换不符合规范的字符转换成国际化公认的URL编码 %20 代表一个空格 (在URLEncoder会把空格变成+)
	 * %7E代表~ %2A代表*(一个乘号)
	 * 
	 * @param value
	 * @return
	 */
	public static String encode(String value)
	{
		String encoded = null;
		try
		{
			encoded = URLEncoder.encode(value, "UTF-8");
		}
		catch (UnsupportedEncodingException ignore)
		{
		}
		StringBuffer buf = new StringBuffer(encoded.length());
		char focus;
		for (int i = 0; i < encoded.length(); i++)
		{
			focus = encoded.charAt(i);
			if (focus == '*')
			{
				buf.append("%2A");
			}
			else if (focus == '+')
			{
				buf.append("%20");
			}
			else if (focus == '%' && (i + 1) < encoded.length() && encoded.charAt(i + 1) == '7'
					&& encoded.charAt(i + 2) == 'E')
			{
				buf.append('~');
				i += 2;
			}
			else
			{
				buf.append(focus);
			}
		}
		return buf.toString();
	}

}